import { CanActivate, ExecutionContext, Injectable ,HttpException,HttpStatus} from '@nestjs/common';
import { Observable } from 'rxjs';
import * as jwt from 'jsonwebtoken'
import {RedisUtilsService} from 'src/modules/redis-utils/redis-utils.service'
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly redisUtilsService:RedisUtilsService){}
  //jwt验证token
//  async canActivate(
//     context: ExecutionContext,
//   ):Promise<boolean> {
//     console.log('守卫',context.switchToHttp().getRequest().headers.token);
//     const request = context.switchToHttp().getRequest()
//     const token = request.headers.token
//     if(token){
//       try {
//         const user =await this.verifyToken(token)
//         request.user = user
//         return true
//       } catch (e) {
//         throw new HttpException('您的登录已过期，请重新登录',HttpStatus.UNAUTHORIZED)
//       }
//     }else{
//        throw new HttpException('你还没有登录，请先登录',HttpStatus.UNAUTHORIZED)
//     }
//   }
//redis验证token
 async canActivate(
    context: ExecutionContext,
  ):Promise<boolean> {
    console.log('守卫',context.switchToHttp().getRequest().headers.token);
    const request = context.switchToHttp().getRequest()
    const token = request.headers.token
    if(token){
      try {
        const user = await this.verifyToken(token)
        const redisData =await this.redisUtilsService.get(String((user as any).id))
        console.log('====redisData=====',redisData);
        if(Object.is(token,(redisData as {[key:string]:any}).token)){
          return true
        }else{
          throw new HttpException('token已失效，请重新登录',HttpStatus.UNAUTHORIZED)
        }
      } catch (e) {
        throw new HttpException(e,HttpStatus.UNAUTHORIZED)
      }
    }else{
       throw new HttpException('你还没有登录，请先登录',HttpStatus.UNAUTHORIZED)
    }
  }

  private verifyToken(token){
    return new Promise((resolve,reject)=>{
      jwt.verify(token,process.env.SECRET,(err,payload)=>{
        if(err){
          console.log('token解析报错================',err);
          reject(err)
        }else{
          resolve(payload)
        }
      })
    })
    
  }
}
